package com.su.fileupload.controller;


import cn.hutool.core.map.MapUtil;
import com.su.fileupload.constant.HttpStatus;
import com.su.fileupload.service.ISysChunkService;
import com.su.fileupload.service.ISysFileService;
import com.su.fileupload.vo.request.FileChunkRequest;
import com.su.fileupload.vo.response.FileChunkCheckResponse;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 文件列表 前端控制器
 * </p>
 *
 * @author susj
 * @since 2023-08-13
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class SysFileController {

    @Resource
    private ISysFileService sysFileService;

    @Resource
    private ISysChunkService sysChunkService;


    /**
     * 获取分片信息
     *
     * @param fileChunkRequest 文件分片信息
     * @return
     */
    @GetMapping("/upload")
    public Map<Object, Object> checkFileChunk(@ModelAttribute FileChunkRequest fileChunkRequest) {
        FileChunkCheckResponse fileChunkCheckResponse = sysChunkService.checkFileChunk(fileChunkRequest);
        return MapUtil.builder().put("code", HttpStatus.SUCCESS).put("data", fileChunkCheckResponse).build();
    }

    /**
     * 分片信息校验之后开始分片上传文件
     *
     * @param fileChunkRequest 文件分片信息
     * @return
     */
    @PostMapping("/upload")
    public Map<Object, Object> chunkUploadFile(@ModelAttribute FileChunkRequest fileChunkRequest) throws IOException {
        FileChunkCheckResponse upload = sysFileService.upload(fileChunkRequest);
        return MapUtil.builder().put("code", HttpStatus.SUCCESS).put("data", upload).build();
    }


    /**
     * 合并分片
     *
     * @param fileChunkRequest 文件分片信息
     * @return
     * @throws IOException
     */
    @PostMapping("/merge")
    public Map<Object, Object> mergeChunk(@RequestBody FileChunkRequest fileChunkRequest) throws IOException {
        sysFileService.merge(fileChunkRequest);
        return MapUtil.builder().put("code", HttpStatus.SUCCESS).build();
    }


}
